/**
 * @version Create on 2012-11-1
 * @author Yinzi Chen
 */

public class EditDistance {

	public int minDistance(String word1, String word2) {
		int n, m;
		n = word1.length();
		m = word2.length();
		if (n == 0 || m == 0)
			return Math.abs(n - m);
		int[][] d = new int[n + 1][m + 1];
		for (int i = 0; i <= n; ++i)
			for (int j = 0; j <= m; ++j)
				d[i][j] = 100000000;
		for (int i = 0; i <= n; ++i) {
			d[i][0] = i;
		}
		for (int i = 0; i <= m; ++i) {
			d[0][i] = i;
		}
		for (int i = 1; i <= n; ++i)
			for (int j = 1; j <= m; ++j) {
				d[i][j] = d[i - 1][j - 1]
						+ (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 1);
				d[i][j] = Math.min(d[i][j], d[i][j - 1] + 1);
				d[i][j] = Math.min(d[i][j], d[i - 1][j] + 1);
			}
		return d[n][m];
	}

	public static void main(String[] args) {
		EditDistance a = new EditDistance();
		a.minDistance("a", "ab");
	}

}
